//
//  DDTextInputView.m
//  DongDongWedding
//
//  Created by 谢曦 on 16/9/12.
//  Copyright © 2016年 gl. All rights reserved.
//

#import "DDTextView.h"
#import "UIView+DDAdd.h"

@interface DDTextView ()<UITextViewDelegate>
@property (nonatomic,weak) UILabel *placeholderLabel;
//@property (nonatomic,assign) BOOL isChineseInput;
@end
@implementation DDTextView
-(instancetype)init
{
    if ([super  init]) {
        
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
       
        
        self.backgroundColor= [UIColor clearColor];
        UILabel *placeholderLabel = [[UILabel alloc] init];        placeholderLabel.textColor=[UIColor lightGrayColor];
        placeholderLabel.font=Font(13);
        
        placeholderLabel.numberOfLines=0;
        [self addSubview:placeholderLabel];
        _placeholderStr=@"请输入...";
        _placeholderLabel= placeholderLabel;
        _placeholderColor= [UIColor  grayColor];
        self.font= Font(13);//默认
//        self.textColor=[DDSkin DDThemeBlackColor];
   
                //  默认占位frame
                self.placeholderLabel.y=8;
                self.placeholderLabel.x=5;
        self.placeholderLabel.width=self.width-self.placeholderLabel.x*2.0; //设置 UILabel 的 x
        _maxlimitedCharacterCount=NSIntegerMax;//默认最大整数
        //根据文字计算高度
        CGSize maxSize =CGSizeMake(self.placeholderLabel.bounds.size.width,MAXFLOAT);
       
        self.placeholderLabel.height= [_placeholderStr boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.placeholderLabel.font} context:nil].size.height;
        self.delegate=self;
        
      
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    /** 当没有手动设置placeholder的frame时, 使用默认的位置.*/
    if (!_placeholderFrame.origin.x) {
        self.placeholderLabel.y=8; //设置UILabel 的 y值 8
        self.placeholderLabel.x=5;//设置 UILabel 的 x 值
        self.placeholderLabel.width=self.width-self.placeholderLabel.x*2.0; //设置 UILabel 的 x
        
        //根据文字计算高度
        CGSize maxSize =CGSizeMake(self.placeholderLabel.width,MAXFLOAT);
        self.placeholderLabel.height= [self.placeholderStr boundingRectWithSize:maxSize options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.placeholderLabel.font} context:nil].size.height;
    }
}




-(void)setText:(NSString *)text
{
    [super setText:text];
_placeholderLabel.hidden=text.length==0?NO:YES;
}
//重新设置占位frame
-(void)setPlaceholderFrame:(CGRect)placeholderFrame
{
    self.placeholderLabel.frame=placeholderFrame;
  
}

-(void)setPlaceholderFont:(UIFont *)placeholderFont
{
    _placeholderFont=placeholderFont;
    self.font=placeholderFont;
  
}

-(void)setPlaceholderHidden:(BOOL)placeholderHidden
{
    self.placeholderLabel.hidden=placeholderHidden;
}


- (void)setPlaceholderStr:(NSString *)placeholderStr{
    _placeholderStr= [placeholderStr copy];
    self.placeholderLabel.hidden = self.text.length!=0?YES:NO;
    self.placeholderLabel.text= placeholderStr;
    //重新计算子控件frame
    [self setNeedsLayout];
}

- (void)setPlaceholderColor:(UIColor *)placeholderColor{
    _placeholderColor= placeholderColor;
    self.placeholderLabel.textColor= placeholderColor;
}


#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
   
  
//    NSString *str=[textView.text stringByReplacingCharactersInRange:range withString:text];
//     NSLog(@"%@---%@---%@",text,textView.text,str);
     if ([text isEqualToString:@"\n"]) {
    if ([self.ddDelegate respondsToSelector:@selector(textViewClickKeyboardDone)]) {
        [self.ddDelegate textViewClickKeyboardDone];
        return NO;
    }
}

    if ([self isChineseInput]==YES) {
        return YES;//中文的话交给textViewDidChange 计算
    }
        NSInteger length = [text length] + [[textView text] length];
    if([text isEqualToString: @""] && length > 0){
        ///当用户使用删除键时
        length -= range.length;
    }
          if (length <= self.maxlimitedCharacterCount){
            return YES;

        }
    else if (length ==self.maxlimitedCharacterCount)
    {
//        [NSObject showHudTipStr:[NSString stringWithFormat:@"字数已达上限%ld", (long)self.maxlimitedCharacterCount]];
        return NO;
    }
       else if (length >self.maxlimitedCharacterCount){
           NSString *completeStr=[NSString stringWithFormat:@"%@%@",textView.text,text];
          NSString *subStr= [completeStr substringWithRange:NSMakeRange(0, _maxlimitedCharacterCount)];
           [textView setText:subStr];
//            [NSObject showHudTipStr:[NSString stringWithFormat:@"字数已达上限%ld", (long)self.maxlimitedCharacterCount]];
            return NO;
        }
    if ([self.ddDelegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)])
        {
            return [self.ddDelegate textView:textView shouldChangeTextInRange:range replacementText:text];
        }
       else return YES;
    
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([self.ddDelegate respondsToSelector:@selector(textViewDidBeginEditing:)]) {
        [self.ddDelegate textViewDidBeginEditing:(DDTextView*)textView];
    }
}



-(BOOL )isChineseInput
{

    NSString *primaryLanguage=  [[UIApplication sharedApplication]textInputMode].primaryLanguage ;
    // 键盘输入语言模式 英语为en-US 如果是中文为zh-Hans 表情 emoji
//    NSLog(@"%@---%@-----%@",primaryLanguage,[UITextInputMode activeInputModes],primaryLanguage);
    return [primaryLanguage isEqualToString:@"zh-Hans"];
}

-(BOOL )isNotHighLightEdtingWithTextView:(UITextView *)textView
{
          UITextRange *selectedRange = [textView markedTextRange];
              //获取高亮部分（就是在编辑蓝色的部分）
                UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
           if(selectedRange && position){
           // 有高亮选择的字符串，则暂不对文字进行统计和限制
            return NO;
        }
       else if (!position) {
    // 非高亮选择的字
            return YES;
        }
       else return NO;
 
}

-(void)textViewDidChange:(UITextView *)textView {
  
     //在这个方法里面算  取到准确的textview.text
    if ([self isChineseInput]==NO) {
        if ([self.ddDelegate respondsToSelector:@selector(textViewDidChange:)]) {
            [self.ddDelegate textViewDidChange:textView];
        }
        return;
    }
  else
  {
      if( [self isNotHighLightEdtingWithTextView:textView]==YES) {
         if (textView.text.length >=_maxlimitedCharacterCount)
        {//此时是非高亮状态
            NSString *subStr= [textView.text substringWithRange:NSMakeRange(0, _maxlimitedCharacterCount)];
            [textView setText:subStr];
//            [NSObject showHudTipStr:[NSString stringWithFormat:@"字数已达上限%ld", (long)self.maxlimitedCharacterCount]];
            self.text=subStr;
           

        }
    }
  }
    
    if ([self.ddDelegate respondsToSelector:@selector(textViewDidChange:)]) {
        [self.ddDelegate textViewDidChange:textView];
    }
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    if ([self.ddDelegate respondsToSelector:@selector(textViewShouldBeginEditing:)]) {
       return  [self.ddDelegate textViewShouldBeginEditing:self];
    
    }
    return YES;
}

- (void)textDidChange {
    self.placeholderLabel.hidden = self.text.length;
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:UITextViewTextDidChangeNotification];
}
@end
